package com.masterclient.app.businessmodule.homemodule.view.adapter.saletab;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.eoner.commonbean.product.ProductMessage;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.homemodule.bean.saletabs.FlashSaleTabBean;
import com.masterclient.app.businessmodule.homemodule.view.holder.HomeViewHolder;
import com.masterclient.app.modules.timelimited.TimeLimitedBuyActivity;
import com.eoner.baselibrary.utils.Utils;

import java.util.ArrayList;
import java.util.List;


public class HomePageXTimeLimitedHeadAdapter extends DelegateAdapter.Adapter<HomeViewHolder>  {

    private Context mContext;
    private LayoutHelper mLayoutHelper;
    private VirtualLayoutManager.LayoutParams mLayoutParams;
    private int mCount = 0;
    private List<FlashSaleTabBean> shTimeProductDataList;
    private OnClickStatusListener clickStatusListener;

    private int select,index;
    private long countDownInterval = 1000;
    private TabLayout tabLayout0;
    private RecyclerView timeRecyclerView;
    private View time_more_layout;
    private View time_limited_title;
    private View time_limited_listview_layout;
    private View time_limited_layout;
    private TextView desc;
    private View day_layout;
    private View time_layout;
    private TextView day;
    private TextView hour;
    private TextView minute;
    private TextView seconds;
    private TimeLimitedProductAdapter adapter;
    private int position;

    public void refreshData(List<FlashSaleTabBean> shTimeProductDataList) {
        this.shTimeProductDataList = shTimeProductDataList;
        notifyDataSetChanged();
    }

    public void refreshChildData(List<FlashSaleTabBean> shTimeProductDataList,String status) {
        if (adapter != null && shTimeProductDataList.size()>0) {
            adapter.refreshData(shTimeProductDataList.get(select).getExtShopList(),shTimeProductDataList.get(select).getEvent_map_id(),shTimeProductDataList.get(select).getStart_time(),status);
        }
    }

    public HomePageXTimeLimitedHeadAdapter(Context context, LayoutHelper layoutHelper, int count, @NonNull VirtualLayoutManager.LayoutParams layoutParams, List<FlashSaleTabBean> shTimeProductDataList) {
        this.mContext = context;
        this.mLayoutHelper = layoutHelper;
        this.mCount = count;
        this.mLayoutParams = layoutParams;
        this.shTimeProductDataList = shTimeProductDataList;
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mLayoutHelper;
    }
    @Override
    protected void onBindViewHolderWithOffset(HomeViewHolder holder, int position, int offsetTotal) {

    }


    public void refreshAll(int count, List<FlashSaleTabBean> shTimeProductDataList) {
        this.mCount = count;
        this.shTimeProductDataList.clear();
        this.shTimeProductDataList = shTimeProductDataList;
        destroy_timer();
        notifyDataSetChanged();
    }


    @Override
    public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }
    @Override
    public void onBindViewHolder(HomeViewHolder holder, int position) {
        if(mLayoutParams!=null) {
            holder.itemView.setLayoutParams(
                    new VirtualLayoutManager.LayoutParams(mLayoutParams));
        }

        tabLayout0 = holder.itemView.findViewById(R.id.tabLayout0);
        timeRecyclerView = holder.itemView.findViewById(R.id.timeRecyclerView);
        time_more_layout = holder.itemView.findViewById(R.id.time_more_layout);
        time_limited_title = holder.itemView.findViewById(R.id.time_limited_title);
        time_limited_listview_layout = holder.itemView.findViewById(R.id.time_limited_listview_layout);
        time_limited_layout = holder.itemView.findViewById(R.id.time_limited_layout);
        desc = holder.itemView.findViewById(R.id.desc);
        day_layout = holder.itemView.findViewById(R.id.day_layout);
        time_layout = holder.itemView.findViewById(R.id.time_layout);
        day = holder.itemView.findViewById(R.id.day);
        hour = holder.itemView.findViewById(R.id.hour);
        minute = holder.itemView.findViewById(R.id.minute);
        seconds = holder.itemView.findViewById(R.id.seconds);


        this.position = position;
        tabLayout0.removeAllTabs();
        if(shTimeProductDataList != null){
            //int select = -1;//默认选中的位置
            for (int i = 0; i < shTimeProductDataList.size(); i++) {
                tabLayout0.addTab(tabLayout0.newTab());
                TabLayout.Tab tab = tabLayout0.getTabAt(i);
                FlashSaleTabBean timeProductData = shTimeProductDataList.get(i);
                if (tab != null) {
                    tab.setCustomView(R.layout.home_time_tab_first_item);
                    View view = tab.getCustomView();
                    TextView startTime = (TextView) view.findViewById(R.id.startTime);
                    TextView status = (TextView) view.findViewById(R.id.status);
                    startTime.setText(timeProductData.getTitle().replaceAll("=>",":"));
                    Utils.setDin(startTime,mContext);
                    status.setText(timeProductData.getSub_title());
                    if (timeProductData.isIs_selected()) {
                        select = i;
                    }
                }
            }
            if (select == -1) {
                select = 0;
            }
            if(shTimeProductDataList.size() > 4){
                tabLayout0.setTabMode (TabLayout.MODE_SCROLLABLE);
                tabLayout0.setTabGravity(TabLayout.GRAVITY_FILL);
            }else{
                tabLayout0.setTabMode (TabLayout.MODE_FIXED);
                tabLayout0.setTabGravity(TabLayout.GRAVITY_FILL);
            }

            if (tabLayout0.getTabAt(select) != null) {
                tabLayout0.getTabAt(select).select();
            }
            set_time_tab0(select,false);


            index = select > 2 ? select - 2 : select;

            if(tabLayout0.getTabCount() > 5){

                tabLayout0.post(()-> {
                    /* 如果各个tab宽度差异太大，就循环累加计算 */

                    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
                    int width = wm.getDefaultDisplay().getWidth() / 5;
                    //int offset = tabLayout0.getChildAt(0).getWidth() * index;
                    int offset = width * index;
                    if(tabLayout0 != null){
                        tabLayout0.smoothScrollTo(offset, 0);
                    }
                });

            }

            List<ProductMessage> shProducts = null;
            String status = "";
            try {
                shProducts = shTimeProductDataList.get(select).getExtShopList();
                status = shTimeProductDataList.get(select).getStatus();
                if(Integer.valueOf(shTimeProductDataList.get(select).getLifetime()) == 0){
                    status = "2";
                }
            } catch (Exception e){
                e.printStackTrace();
            }
            if(shProducts == null){
                shProducts = new ArrayList<>();
            }
            adapter = new TimeLimitedProductAdapter(mContext,shProducts,status,"首页", shTimeProductDataList.get(select).getStart_time(),shTimeProductDataList.get(select).getEvent_map_id());

            adapter.setOnClickStatusListener(new TimeLimitedProductAdapter.OnClickStatusListener() {
                @Override
                public void clickStatusBtn(String type, String productId,String eventId,String startTime) {
                    clickStatusListener.clickStatusBtn(type,productId,eventId,select,startTime);
                }
            });


            LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext){
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            timeRecyclerView.setLayoutManager(mLayoutManager);
            timeRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        if(shTimeProductDataList == null || shTimeProductDataList.size() == 0){
            time_more_layout.setVisibility(View.GONE);
            tabLayout0.setVisibility(View.GONE);
            time_limited_title.setVisibility(View.GONE);
            time_limited_listview_layout.setVisibility(View.GONE);
            time_limited_layout.setVisibility(View.GONE);
        }else{
            time_more_layout.setVisibility(View.VISIBLE);
            tabLayout0.setVisibility(View.VISIBLE);
            time_limited_title.setVisibility(View.VISIBLE);
            time_limited_listview_layout.setVisibility(View.VISIBLE);
            time_limited_layout.setVisibility(View.VISIBLE);
        }

        time_more_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext,TimeLimitedBuyActivity.class);
                intent.putExtra("intentSource","首页");
                mContext.startActivity(intent);
            }
        });

        tabLayout0.clearOnTabSelectedListeners();
        tabLayout0.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();

                set_time_tab0(position,true);

                String status =shTimeProductDataList.get(position).getStatus();
                if(Integer.valueOf(shTimeProductDataList.get(position).getLifetime()) == 0){
                    status = "2";
                }

                //TODO:这里有值直接调，没值要调接口刷新
                List<ProductMessage>shopCommonItemBeans = shTimeProductDataList.get(position).getExtShopList();
                if (shopCommonItemBeans != null && shopCommonItemBeans.size() > 0) {
                    adapter = new TimeLimitedProductAdapter(mContext,shTimeProductDataList.get(position).getExtShopList(),status, "首页", shTimeProductDataList.get(position).getStart_time(),shTimeProductDataList.get(position).getEvent_map_id());

                    adapter.setOnClickStatusListener(new TimeLimitedProductAdapter.OnClickStatusListener() {
                        @Override
                        public void clickStatusBtn(String type, String productId,String eventId,String startTime) {
                            clickStatusListener.clickStatusBtn(type,productId,eventId,position,startTime);
                        }
                    });

                    LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
                    timeRecyclerView.setLayoutManager(mLayoutManager);
                    timeRecyclerView.setAdapter(adapter);
                } else {
                    FlashSaleTabBean timeProductData = shTimeProductDataList.get(select);
                    if (clickStatusListener != null) {
                        clickStatusListener.onClickTab(timeProductData.getEvent_map_id(),select,status);
                    }
                }
            }


            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    private List<CountDownTimer> countDownTimers = new ArrayList<>();

    public void initCountDownTimer(){
        destroy_timer();
        countDownTimers.clear();
        for (int i = 0; i < shTimeProductDataList.size(); i++) {
            FlashSaleTabBean timeProductData = shTimeProductDataList.get(i);
            long millisInFuture = Long.valueOf(timeProductData.getLifetime()) * 1000;

            String status = timeProductData.getStatus();
            if(millisInFuture != 0){
                int finalI = i;
                CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        if (timeProductData != null) {
                            timeProductData.setLifetime(String.valueOf(millisUntilFinished/1000));
                        }
                        if(finalI != select){
                            return;
                        }
                        updateTime(millisUntilFinished,status);
                    }

                    @Override
                    public void onFinish() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //TODO: 暂时去掉刷新
//                                //调接口刷新
//                                if (clickStatusListener != null) {
//                                    clickStatusListener.onRefreshData();
//                                }
                            }
                        },1000);
                    }
                };
                timer.start();
                countDownTimers.add(timer);
            } else if(i == select){
                if (desc != null) {
                    desc.setText("本场已结束,下次早点吧～");
                    day_layout.setVisibility(View.GONE);
                    time_layout.setVisibility(View.GONE);
                }
            }
        }
    }

    private void updateTime(long millisUntilFinished,String status) {
        if (day_layout != null) {
            int day_ = (int) (millisUntilFinished /(1000 * 60 * 60 * 24));
            int dayLeft = (int) (millisUntilFinished %(1000 * 60 * 60 * 24));
            int hour_ = (int) (dayLeft /(1000 * 60 * 60));
            int houtLeft = (int) (millisUntilFinished % (1000 * 60 * 60));
            int minute_ = (int) (houtLeft /(1000 * 60));
            int minuteLeft = (int) (millisUntilFinished % (1000 * 60 ));
            int seconds_ = (int) (minuteLeft /(1000));
            int secondsLeft = (int) (minuteLeft % (1000));
            if(day_ == 0){
                day_layout.setVisibility(View.GONE);
            }else{
                day_layout.setVisibility(View.VISIBLE);
            }
            setTimeText(day,day_);
            setTimeText(hour,hour_);
            setTimeText(minute,minute_);
            setTimeText(seconds,seconds_);

            if("3".equals(status) || "1".equals(status)){
                desc.setText("距本场结束");
            }else if("4".equals(status) | "5".equals(status)){
                desc.setText("距本场开始");
            }
        }

    }

    public void destroy_timer() {
        for(CountDownTimer timer : countDownTimers){
            if(timer != null){
                timer.cancel();
                timer = null;
            }
        }
    }

    private void setTimeText(TextView day, int day_) {
        if(("" + day_).length() == 1){
            day.setText("0" + day_);
        }else{
            day.setText("" + day_);
        }
    }

    private void set_time_tab0(int position, boolean isClick) {
        select = position;
        for (int i = 0; i < tabLayout0.getTabCount(); i++) {
            //TimeVenue timeVenue = timeVenues.get(i);
            View view = tabLayout0.getTabAt(i).getCustomView();
            if (view == null) {
                return;
            }
            TextView startTime = (TextView) view.findViewById(R.id.startTime);
            TextView status = (TextView) view.findViewById(R.id.status);
            if ("售罄".equals("") && (position != i)) {
                startTime.setTextColor(Color.parseColor("#999999"));
                status.setTextColor(Color.parseColor("#999999"));
            } else {
                if (position == i) {
                    startTime.setTextColor(Color.parseColor("#F23051"));
                    status.setTextColor(Color.parseColor("#F23051"));
                    startTime.setTextSize(21);
                    status.setTextSize(12);

                    FlashSaleTabBean timeProductData = shTimeProductDataList.get(select);
                    long millisInFuture = Long.valueOf(timeProductData.getLifetime()) * 1000;
                    if(millisInFuture == 0) {
                        desc.setText("本场已结束,下次早点吧～");
                        day_layout.setVisibility(View.GONE);
                        time_layout.setVisibility(View.GONE);
                    } else {
                        //预加载
                        updateTime(millisInFuture,timeProductData.getStatus());
//                        updateTime(millisInFuture,);
//                        desc.setText("");
//                        day_layout.setVisibility(View.VISIBLE);
                        time_layout.setVisibility(View.VISIBLE);
                    }
                } else {
                    startTime.setTextColor(Color.parseColor("#999FAA"));
                    status.setTextColor(Color.parseColor("#999FAA"));
                    startTime.setTextSize(15);
                    status.setTextSize(12);
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return mCount;
    }

    @Override
    public int getItemViewType(int position) {
        return 12;
    }

    public void setOnClickStatusListener(OnClickStatusListener clickStatusListener){
        this.clickStatusListener = clickStatusListener;
    }

    public interface OnClickStatusListener{
        void clickStatusBtn(String type,String productId,String mapId,int childPosition,String startTime);
        void onClickTab(String mapId,int selIndex,String status);
        void onRefreshData();
    }
}
